package icu.wdtt.Interceptors;

import com.fasterxml.jackson.databind.ObjectMapper;
import icu.wdtt.Utils.RandomCodeUtils;
import icu.wdtt.Utils.ResultUtils;
import icu.wdtt.enumModel.HttpRequestMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class CheckCodeInterceptor implements HandlerInterceptor {
    @Autowired
    private ResultUtils resultUtils;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //这是请求头和返回头的字符格式以及响应头的信息
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        //创建Jackson解析器对象对象
        ObjectMapper mapper = new ObjectMapper();
        //获取用户输入的验证码
        String checkCode = request.getParameter("checkCode");
        //获取验证码token
        String checkId  = request.getParameter("checkId");
        if(checkCode !=null && checkCode.length() == 4){
            //验证是否正确
            boolean flag = RandomCodeUtils.checkRandomCode(checkId,checkCode);
            //移除该验证码
            RandomCodeUtils.removeRandomCode(checkId);
            if(flag){
                return true;
            }
        }
        mapper.writeValue(response.getWriter(),resultUtils.fail(HttpRequestMessage.FAIL_CHECK_CODE));
        return false;
    }
}